package com.lg.util;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.lg.model.exception.ContentTypeNotSupportException;
import com.lg.model.exception.FileIsNullException;
import com.lg.model.exception.FileOutOfMaxLengthException;

public class MultipartFileValidator {
	private final static long MAX_SIZE = 1024 * 1024;

	private String filePath;
	/**
	 * 文件大小上限
	 */
	private long maxSize = MAX_SIZE;

	/**
	 * 可接受的文件content-type
	 */
	private String[] allowedContentTypes;

	@PostConstruct
	public void afterPropertiesSet() {
		Assert
				.notEmpty(allowedContentTypes,
						"The content types allowed to be uploaded must contain one at least!");
	}

	/**
	 * 验证上传文件是否合法，如果不合法那么会抛出异常
	 * 
	 * @param file
	 *            用户上传的文件封装类
	 * @throws ContentTypeNotSupportException
	 * @throws FileIsNullException 
	 * @throws FileOutOfMaxLengthException
	 */
	public void validate(MultipartFile file)
			throws ContentTypeNotSupportException, FileIsNullException {
        if(file.isEmpty())
        	throw new FileIsNullException("文件不能为空!");
		if (!ArrayUtils.contains(allowedContentTypes, file.getContentType()))
			throw new ContentTypeNotSupportException("文件格式不正确!");
	}

	/**
	 * 设置文件上传大小上限
	 * 
	 * @param maxSize
	 *            文件上传大小上限
	 */
	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	/**
	 * 设置可接受的文件content-type数组
	 * 
	 * @param allowedContentTypes
	 *            可接受的文件content-type数组
	 */
	public void setAllowedContentTypes(String[] allowedContentTypes) {
		this.allowedContentTypes = allowedContentTypes;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
}
